package com.gj.reggie.common;

import com.gj.reggie.constant.ExceptionConstant;
import com.gj.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 郭嘉
 * @date 2022/12/8 - 21:53
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理方法，该方法处理元数据项重复
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        if(exception.getMessage().contains(ExceptionConstant.DUPLICATE_ENTRY)){
            String []spilt=exception.getMessage().split(" ");
            String msg=spilt[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    /**
     * 异常处理方法，该方法处理业务异常
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){

        return R.error(exception.getMessage());
    }
}
